package com.express.boot.controller;

import com.express.boot.utils.file.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
public class DruidSqlController {
    /**
     * 文件后缀
     */
    public static final String FILE_SUFFIX = ".sql";
    /**
     * 数据库用户名
     */
    @Value("${spring.datasource.username}")
    private String userName;
    /**
     * 数据库密码
     */
    @Value("${spring.datasource.password}")
    private String password;
    /**
     * 数据库url
     */
    @Value("${spring.datasource.url}")
    private String url;
    private String windowsPath = "d:/test/";
    private String linuxPath = "/usr";

    /**
     * 判断操作系统类型、Linux|Windows
     */
    public static boolean isSystem(String osName) {
        Boolean flag = null;
        if (osName.startsWith("windows")) {
            flag = true;
        } else if (osName.startsWith("linux")) {
            flag = false;
        }
        return flag;
    }

    @GetMapping("/system/druidSql")
    public String druidSql() {
        return "http://localhost:8181/druid";
    }

    @PostMapping("/mysqlBackups")
    public Object mysqlBackups() {
        String path = null;
        // 获取操作系统名称
        String osName = System.getProperty("os.name").toLowerCase();
        if (isSystem(osName)) {
            // Windows
            path = this.windowsPath;
        } else {
            // Linux
            path = this.linuxPath;
        }
        // 数据库用户名
        String userName = this.userName;
        // 数据库密码
        String password = this.password;
        // 数据库地址
        String url = this.url;
        // 调用备份
        Object systemMysqlBackups = mysqlBackups(path, url, userName, password);
        return systemMysqlBackups;
    }

    public Object mysqlBackups(String filePath, String url, String userName, String password) {
        // 获取ip
        final String ip = url.substring(13, 22);
        // 获取端口号
        final String port = url.substring(23, 27);
        // 获取数据库名称
        final String database_name = url.substring(28, 42);
        // 数据库文件名称
        StringBuilder mysqlFileName = new StringBuilder()
                .append("cc")
                .append("_")
                .append(new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()))
                .append(".sql");
        // 备份命令
        StringBuilder cmd = new StringBuilder()
                .append("mysqldump ")
                .append("--no-tablespaces ")
                .append("-h")
                .append(ip)
                .append(" -u")
                .append(userName)
                .append(" -p")
                .append(password)
                // 排除MySQL备份表
                .append(" --ignore-table ")
                .append(database_name)
                .append(".mysql_backups ")
                .append(database_name)
                .append(" > ")
                .append(filePath)
                .append(mysqlFileName);


        // 获取操作系统名称
        String osName = System.getProperty("os.name").toLowerCase();
        String[] command = new String[0];
        if (isSystem(osName)) {
            // Windows
            command = new String[]{"cmd", "/c", String.valueOf(cmd)};
        } else {
            // Linux
            command = new String[]{"/bin/sh", "-c", String.valueOf(cmd)};
        }
//        SystemMysqlBackups smb = new SystemMysqlBackups();
//        // 备份信息存放到数据库
//        smb.setMysqlIp(ip);
//        smb.setMysqlPort(port);
//        smb.setBackupsName(String.valueOf(mysqlFileName));
//        smb.setDatabaseName(database_name);
//        smb.setMysqlCmd(String.valueOf(cmd));
//        smb.setBackupsPath(filePath);
//        smb.setCreateTime(DateTime.now());
//        smb.setStatus(1);
//        smb.setOperation(0);
//        systemMysqlBackupsMapper.insert(smb);
//        log.error("数据库备份命令为：{}", cmd);
        // 获取Runtime实例
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            if (process.waitFor() == 0) {
                return "成功" + mysqlFileName;
//                log.info("Mysql 数据库备份成功,备份文件名：{}", mysqlFileName);
            } else {
                return "失败网络异常" + mysqlFileName + cmd;
//                return new ErrorTip(HttpStatus.INTERNAL_SERVER_ERROR.value(), "网络异常，数据库备份失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "失败网络异常" + mysqlFileName + e.getMessage();
//            return new ErrorTip(HttpStatus.INTERNAL_SERVER_ERROR.value(), "网络异常，数据库备份失败");
        }
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception("文件名称({})非法，不允许下载。 " + fileName);
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = "D:/text/uploadPath" + "/download/" + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            System.out.println("下载文件失败");
        }
    }

}
